package JUC.forkjoin;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

public class Demo {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        test1();
        test2();
        test3();
    }

    //普通执行
    public static void test1() {
        long start = System.currentTimeMillis();
        int sum = 0;
        for (int i = 0; i < 10_0000_0000L; i++) {
            sum += i;
        }
        long end = System.currentTimeMillis();
        System.out.println("sum=" + (end - start) + "时间");
    }

    //forkjoin执行
    public static void test2() throws ExecutionException, InterruptedException {
        long start = System.currentTimeMillis();

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinTask<Long> task = new ForkJoinDemo(0, 10_0000_0000L);
        //forkJoinPool.execute(task);//执行
        ForkJoinTask<Long> submit = forkJoinPool.submit(task);//异步提交

        submit.get();

        long end = System.currentTimeMillis();
        System.out.println("sum=" + (end - start) + "时间");
    }

    //stream并行流
    public static void test3() {
        long start = System.currentTimeMillis();

        //stream并行流
        LongStream.rangeClosed(0L,10_0000_0000L).reduce(0,Long::sum);

        long end = System.currentTimeMillis();
        System.out.println("sum=" + (end - start) + "时间");
    }
}
